package com.cah.project.mock.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 功能描述: 本项目的字符串工具类，扩展hutool的StrUtil <br/>
 */
public class GenStrUtil extends StrUtil {

    /**
     * 功能描述: 获取类型简称 <br/>
     *
     * @param type 类型
     * @return "java.lang.String"
     */
    public static String getTypeSimpleName(Type type) {
        String typeName = type.getTypeName();
        // 是否存在泛型，如 List<E>, Map<K,V>等
        if(typeName.contains("<")) {
            String child = typeName.substring(typeName.indexOf("<") + 1, typeName.indexOf(">"));
            String[] children = child.split(",");
            typeName = typeName.substring(0, typeName.indexOf("<"));
            return typeName.substring(typeName.lastIndexOf(".") + 1) +
                    "<" + Stream.of(children).map(c -> c.substring(c.lastIndexOf(".") + 1)).collect(Collectors.joining(", ")) + ">";
        } else {
            return typeName.substring(typeName.lastIndexOf(".") + 1);
        }
    }

    /**
     * 功能描述: 获取java类原本引入的包 <br/>
     *
     * @param projectName 项目模块名称
     * @param clazz java类
     * @return "java.lang.String"
     */
    public static String getClassImport(String projectName, Class<?> clazz) {
        File javaFile = new File(getJavaFilePath(projectName, clazz));
        try(BufferedReader reader = FileUtil.getUtf8Reader(javaFile)) {
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                if(line.indexOf("import ") == 0) {
                    sb.append(line).append("\n");
                }
                if(line.contains("public")) {
                    break;
                }
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 功能描述: 获取java文件类路径 <br/>
     *
     * @param projectName 项目模块名称
     * @param clazz java类
     * @return "java.lang.String"
     */
    public static String getJavaFilePath(String projectName, Class<?> clazz) {
        return getProjectModulePath(projectName) + File.separator +
                "src\\main\\java\\" +
                clazz.getName().replaceAll("\\.", "\\\\") + ".java";
    }

    /**
     * 功能描述: 获取项目模块路径 <br/>
     *
     * @param projectName 项目模块名称
     * @return "java.lang.String"
     */
    public static String getProjectModulePath(String projectName) {
        return System.getProperty("user.dir") + File.separator + projectName;
    }

}
